axios.defaults.baseURL="http://localhost:8080";
Vue.prototype.$http=axios;

//======================axios的前置拦截器【拦截调用后端的请求====================//
axios.interceptors.request.use(res=>{
  let token = localStorage.getItem("token");
  if(token){
    //将token放在请求头：key：value = 【"token"：7de5e886-49fc-4c76-bc8d-e856193d7103】
    res.headers["token"] = token;
  }
  return res;
},error => {
  Promise.reject(error)
})
//======================axios的前置拦截器【拦截调用后端的请求】====================//
//======================axios的后置拦截器【处理后台登录拦截的结果】====================//
//在回调函数之前就会执行
axios.interceptors.response.use(res => {
  //后端响应的是没有登录的信息
  if (false === res.data.success && "noLogin" === res.data.msg) {
    localStorage.removeItem("token");
    localStorage.removeItem("logininfo");
    //跳转到登录页面
    location.href='index.html';
  } else if (false === res.data.success && "timeout" === res.data.msg){
    alert("登录过期");
    location.href='index.html';
  }
  return res;
},error => {
  Promise.reject(error)
})
//======================axios的后置拦截器【处理后台登录拦截的结果】====================//
var url = location.href;
if (url.indexOf("login.html")== -1 && url.indexOf("register.html")==-1 &&
    url.indexOf("binder.html")== -1 && url.indexOf("callback.html")== -1){

    var logininfo = localStorage.getItem("logininfo");
    if (!logininfo){
        location.href="login.html";
    }
}


//封装公用方法 - 将字符串的参数解析为json对象
function parseUrlParams2Obj(url) {//xxx?code=xxx&state=1
  let paramStr = url.substring(url.indexOf("?")+1);//code=xxx&state=1
  let paramArr = paramStr.split("&");//[code=xxx,state=1]
  let paramObj = {};
  for(let i = 0;i<paramArr.length;i++){
    let paramTemp = paramArr[i];//code=xxx
    let paramName = paramTemp.split("=")[0];//code
    let paramValue= paramTemp.split("=")[1];//xxx
    paramObj[paramName] = paramValue;//{code:xxx,state:1}
  }
  return paramObj;
}
